import React from 'react';
import propTypes from 'prop-types';
import HotTable from 'react-handsontable';

import * as util from './util';
import './extend';
import './index.less';

class Sheet extends React.Component {
  static defaultProps = {
    /** 默认行数 */
    defaultRow: 10,
    /** 显示行号*/
    rowHeaders: true,
    autoAddRow: true,
    contextMenu: [],
    beforeChange: () => { },
    afterChange: () => { },
  }
  constructor(prop) {
    super(prop);
    this.state = {};
  }

  getSheet() {
    return this.sheet.hotInstance;
  }

  getData() {
    return this.getSheet().getData();
  }

  validateCells() {
    return this.getSheet().validateCells();
  }

  render() {
    const { columns, datas, defaultRow, autoAddRow, beforeChange, afterChange, rowHeaders, contextMenu } = this.props;
    return (
      <div>
        <HotTable
          root="hot"
          ref={sheet => (this.sheet = sheet)}
          data={util.renderDatas(datas, defaultRow, autoAddRow)}
          rowHeaders={rowHeaders}
          colHeaders={index => util.renderHeader(columns, index)}
          columns={util.renderColumns(columns)}
          beforeChange={beforeChange}
          afterChange={afterChange}
          stretchH="all"
          headerTooltips={{
            rows: false,
            columns: true,
            onlyTrimmed: true
          }}
          contextMenu={contextMenu}
        />
      </div>
    );
  }

}
/** 定义propTypes */
Sheet.propTypes = {
  /** contextMenu */
  contextMenu: propTypes.any,
  /** Sheet的列配置 */
  columns: propTypes.array.isRequired,
  /** Sheet的数据 */
  datas: propTypes.array.isRequired,
  /** Sheet的默认行 */
  defaultRow: propTypes.number,
  /** Sheet是否显示行号 */
  rowHeaders: propTypes.bool,
  /** 自动增加空行 */
  autoAddRow: propTypes.bool,
  /** beforeChange */
  beforeChange: propTypes.func,
  /** beforeChange */
  afterChange: propTypes.func,
};

export default Sheet;
